﻿using DiaoPaiDaYin;
using DXApplicationTangche.DTO.尖山;
using DXApplicationTangche.model;
using DXApplicationTangche.UC.门店下单.DTO;
using DXApplicationTangche.UC.面料库存;
using DXApplicationTangche.Utils;
using Microsoft.Office.Interop.Excel;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using WindowsFormsApp1;
using Application = Microsoft.Office.Interop.Excel.Application;
using OpenFileDialog = System.Windows.Forms.OpenFileDialog;

namespace DXApplicationTangche.service
{
    class FileService
    {
        /// <summary>
        /// 根据MIME生成文件流字符串,选图片插入用
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="strFilter">"(*xlsx;*.xls;*.docx;*.doc;*.pdf)|*xlsx;*.xls;*.docx;*.doc;*.pdf"</param>
        public static ImageUtil updateTempalteFile(String strFilter, ImageUtil imageUtil)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "请选择文件";
            if (!String.IsNullOrEmpty(strFilter))
            {
                ofd.Filter = strFilter;
            }
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Image image = Image.FromFile(ofd.FileName);
                Byte[] byteArray = FileBinaryConvertHelper.File2Bytes(ofd.FileName);
                return new ImageUtil(
                    Convert.ToBase64String(byteArray)
                    , image
                    );
            }
            else
            {
                return imageUtil;
            }
        }

        /// <summary>
        /// 文件流字符串转图片
        /// </summary>
        /// <param name="fileIOStream"></param>
        /// <returns></returns>
        public static Image convertToImage(String fileIOStream)
        {
            try
            {
                MemoryStream ms = new MemoryStream(Convert.FromBase64String(fileIOStream));
                ms.Position = 0;
                Image img = Image.FromStream(ms);
                ms.Close();
                return img;
            }
            catch
            {
                return null;
            }
        }

        /*
        public static void uploadTaskFile(String taskId, String empId)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "请选择文件";
            ofd.Filter = "(*xlsx;*.xls;*.docx;*.doc;*.pdf)|*xlsx;*.xls;*.docx;*.doc;*.pdf";
            //ofd.ShowDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Byte[] byteArray = FileBinaryConvertHelper.File2Bytes(ofd.FileName);
                String fileStr = Convert.ToBase64String(byteArray);

                String uuid = System.Guid.NewGuid().ToString("N");
                string sql = "insert into file (id,filename,file)"
                    + " values('" + uuid + "'"
                    + "         , '" + ofd.SafeFileName + "'"
                    + "         , '" + fileStr + "'); ";
                DBUtil.ExecuteSQL(sql);
                sql = "update custom_appointment_assignee"
                    + " set file_id = '" + uuid + "'"
                    + " , status = '" + (int)EnumAssignment.已完成 + "'"
                    + " where task_id = '" + taskId + "' and emp_id = '" + empId + "'; ";
                int i = DBUtil.ExecuteSQL(sql);
                //int i = DocService.UpdataMoBan(str, ofd.SafeFileName, fileName);
                if (i != 0)
                {
                    MessageBox.Show("上传成功");
                }
            }
        }*/
        
        /// <summary>
        /// 通过URL返回image
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static Image GetImageByUrl(String url)
        {
            System.Net.WebRequest webreq = System.Net.WebRequest.Create(url);
            System.Net.WebResponse webres = webreq.GetResponse();
            using (System.IO.Stream stream = webres.GetResponseStream())
            {
                return Image.FromStream(stream);
            }
        }
        /// <summary>
        /// 传文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string UploadRequest(string url, string path, string name,string fileN)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.MaximumResponseHeadersLength = 1024;
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=----WebKitFormBoundary" + boundary;
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n------WebKitFormBoundary" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n------WebKitFormBoundary" + boundary + "--\r\n");
            int pos = path.LastIndexOf("\\");
            string fileName = path.Substring(pos + 1);
            //请求头部信息 
            StringBuilder sbHeader = new StringBuilder(
                string.Format(
                    "Content-Disposition:form-data;name=\""+ fileN + "\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n"
                    , fileName
                    ));
            StringBuilder sbHeader2 = new StringBuilder("Content-Disposition:form-data;name=\"name\"\r\n\r\n");
            byte[] namebyte = Encoding.UTF8.GetBytes(name);
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
            byte[] postHeaderBytes2 = Encoding.UTF8.GetBytes(sbHeader2.ToString());
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] bArr = new byte[fs.Length];
            fs.Read(bArr, 0, bArr.Length);
            fs.Close();
            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(bArr, 0, bArr.Length);
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes2, 0, postHeaderBytes2.Length);
            postStream.Write(namebyte, 0, namebyte.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            string header = "\r\n----WebKitFormBoundary" + boundary + "\r\n" + sbHeader.ToString() + " xx " + "\r\n----WebKitFormBoundary" + boundary + "\r\n" + sbHeader2.ToString() + "test234" + "\r\n----WebKitFormBoundary" + boundary + "--\r\n";
            postStream.Close();
            HttpWebResponse res;
            try
            {
                res = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                res = (HttpWebResponse)ex.Response;
            }
            StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
            string content = sr.ReadToEnd();
            return content;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="uploadfile"></param>
        /// <param name="url"></param>
        /// <param name="querystring"></param>
        /// <param name="cookies"></param>
        /// <param name="fileFormName"></param>
        /// <param name="contenttype"></param>
        /// <returns></returns>
        public string UploadFile(string uploadfile, string url, NameValueCollection querystring, CookieContainer cookies, string fileFormName, string contenttype = "multipart/form-data")
        {
            if ((fileFormName == null) ||
                    (fileFormName.Length == 0))
            {
                fileFormName = "file";
            }

            if ((contenttype == null) ||
                (contenttype.Length == 0))
            {
                contenttype = "application/octet-stream";
            }
            Uri uri = new Uri(url);
            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
            webrequest.CookieContainer = cookies;
            webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
            webrequest.Method = "POST";
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append(fileFormName);
            sb.Append("\"; filename=\"");
            sb.Append(uploadfile);
            sb.Append("\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: ");
            sb.Append(contenttype);
            sb.Append("\r\n");
            sb.Append("\r\n");

            string postHeader = sb.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            byte[] br = Encoding.ASCII.GetBytes("\r\n");
            FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
            long length = postHeaderBytes.Length + fileStream.Length + br.Length;
            if (querystring != null)
            {

                StringBuilder sub = new StringBuilder();
                foreach (string key in querystring.Keys)
                {
                    sub.Append("--");
                    sub.Append(boundary);
                    sub.Append("\r\n");
                    sub.Append("Content-Disposition: form-data; name=\"");
                    sub.Append(key);
                    sub.Append("\"");
                    sub.Append("\r\n");
                    sub.Append("\r\n");
                    sub.Append(querystring[key]);
                    sub.Append("\r\n");
                    byte[] formitembytes = Encoding.UTF8.GetBytes(sub.ToString());
                    length += formitembytes.Length;
                }
            }
            length += boundaryBytes.Length;
            webrequest.ContentLength = length;
            Stream requestStream = webrequest.GetRequestStream();
            // Write out our post header
            requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

            // Write out the file contents
            byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                requestStream.Write(buffer, 0, bytesRead);
            requestStream.Write(br, 0, br.Length);
            if (querystring != null)
            {
                StringBuilder sub = new StringBuilder();
                foreach (string key in querystring.Keys)
                {
                    sub.Append("--");
                    sub.Append(boundary);
                    sub.Append("\r\n");
                    sub.Append("Content-Disposition: form-data; name=\"");
                    sub.Append(key);
                    sub.Append("\"");
                    sub.Append("\r\n");
                    sub.Append("\r\n");
                    sub.Append(querystring[key]);
                    sub.Append("\r\n");
                    byte[] formitembytes = Encoding.UTF8.GetBytes(sub.ToString());
                    requestStream.Write(formitembytes, 0, formitembytes.Length);
                }
            }
            // Write out the trailing boundary
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            webrequest.Timeout = 1000000;

            WebResponse responce = webrequest.GetResponse();

            Stream s = responce.GetResponseStream();

            StreamReader sr = new StreamReader(s);

            string str = sr.ReadToEnd();


            fileStream.Close();

            requestStream.Close();

            sr.Close();

            s.Close();

            responce.Close();

            return str;

        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeOut"></param>
        /// <param name="fileKeyName"></param>
        /// <param name="filePath"></param>
        /// <param name="stringDict"></param>
        /// <returns></returns>
        public static string HttpPostData(string url, int timeOut, string fileKeyName,
                      string filePath, NameValueCollection stringDict)
        {
            string responseContent;
            var memStream = new MemoryStream();
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

            // 设置属性
            webRequest.Method = "POST";
            webRequest.Timeout = timeOut;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            // 写入文件
            const string filePartHeader =
        "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
        "Content-Type: application/octet-stream\r\n\r\n";
            var header = string.Format(filePartHeader, fileKeyName, filePath);
            var headerbytes = Encoding.UTF8.GetBytes(header);

            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            var buffer = new byte[1024];
            int bytesRead; // =0

            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }

            // 写入字符串的Key
            var stringKeyHeader = "\r\n--" + boundary +
                 "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                 "\r\n\r\n{1}\r\n";

            foreach (byte[] formitembytes in from string key in stringDict.Keys
                                             select string.Format(stringKeyHeader, key, stringDict[key])
                              into formitem
                                             select Encoding.UTF8.GetBytes(formitem))
            {
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }

            // 写入最后的结束边界符
            memStream.Write(endBoundary, 0, endBoundary.Length);

            webRequest.ContentLength = memStream.Length;

            var requestStream = webRequest.GetRequestStream();

            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();

            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();

            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                    Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }

            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();

            return responseContent;
        }

        public static void SaveDataToExcelFile(List<坚山美国订单回执数据> Dtos, string filePath)
        {
            object misValue = System.Reflection.Missing.Value;
            Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
            Worksheet xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);

            //PropertyInfo[] props = GetPropertyInfoArray();
            //for (int i = 0; i < props.Length; i++)
            //{
            //    xlWorkSheet.Cells[1, i + 1] = props[i].Name; //write the column name
            //}
            xlWorkSheet.Cells[1, 1] = "No.";
            xlWorkSheet.Cells[1, 2] = "Order_No";
            xlWorkSheet.Cells[1, 3] = "Order # ";
            xlWorkSheet.Cells[1, 4] = "Customer Name";
            xlWorkSheet.Cells[1, 5] = "Item";
            xlWorkSheet.Cells[1, 6] = "Fabric Number";
            xlWorkSheet.Cells[1, 7] = "Order Date";
            xlWorkSheet.Cells[1, 8] = "Staff Name";
            xlWorkSheet.Cells[1, 9] = "Quantity";
            xlWorkSheet.Cells[1, 10] = "Email Address";
            xlWorkSheet.Cells[1, 11] = "Mobile Number";
            xlWorkSheet.Cells[1, 12] = "Street Address";
            xlWorkSheet.Cells[1, 13] = "City";
            xlWorkSheet.Cells[1, 14] = "State";
            xlWorkSheet.Cells[1, 15] = "Zip Code";
            xlWorkSheet.Cells[1, 16] = "Color";
            xlWorkSheet.Cells[1, 17] = "Pattern";
            xlWorkSheet.Cells[1, 18] = "Price";
            xlWorkSheet.Cells[1, 19] = "Option";
            xlWorkSheet.Cells[1, 20] = "Subtotal";
            xlWorkSheet.Cells[1, 21] = "Tax";
            xlWorkSheet.Cells[1, 22] = "Total Price";
            for (int i = 0; i < Dtos.Count; i++)
            {
                xlWorkSheet.Cells[i + 2, 1] = Dtos[i].No;
                xlWorkSheet.Cells[i + 2, 2] = Dtos[i].Order_No;
                xlWorkSheet.Cells[i + 2, 3] = Dtos[i].Order_;
                xlWorkSheet.Cells[i + 2, 4] = Dtos[i].Customer_Name;
                xlWorkSheet.Cells[i + 2, 5] = Dtos[i].Item;
                xlWorkSheet.Cells[i + 2, 6] = Dtos[i].Fabric_Number;
                xlWorkSheet.Cells[i + 2, 7] = Dtos[i].Order_Date;
                xlWorkSheet.Cells[i + 2, 8] = Dtos[i].Staff_Name;
                xlWorkSheet.Cells[i + 2, 9] = Dtos[i].Quantity;
                xlWorkSheet.Cells[i + 2, 10] = Dtos[i].Email_Address;
                xlWorkSheet.Cells[i + 2, 11] = Dtos[i].Mobile_Number;
                xlWorkSheet.Cells[i + 2, 12] = Dtos[i].Street_Address;
                xlWorkSheet.Cells[i + 2, 13] = Dtos[i].City;
                xlWorkSheet.Cells[i + 2, 14] = Dtos[i].State;
                xlWorkSheet.Cells[i + 2, 15] = Dtos[i].Zip_Code;
                xlWorkSheet.Cells[i + 2, 16] = Dtos[i].Color;
                xlWorkSheet.Cells[i + 2, 17] = Dtos[i].Pattern;
                xlWorkSheet.Cells[i + 2, 18] = Dtos[i].Price;
                xlWorkSheet.Cells[i + 2, 19] = Dtos[i].Option;
                xlWorkSheet.Cells[i + 2, 20] = Dtos[i].Subtotal;
                xlWorkSheet.Cells[i + 2, 21] = Dtos[i].Tax;
                xlWorkSheet.Cells[i + 2, 22] = Dtos[i].Total_Price;
            }
            try
            {
                xlWorkBook.SaveAs(filePath, XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();
            }
            catch (Exception ex)
            { }

        }
        public static PropertyInfo[] GetPropertyInfoArray()
        {
            PropertyInfo[] props = null;
            try
            {
                Type type = typeof(坚山美国订单回执数据);
                object obj = Activator.CreateInstance(type);
                props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
            catch (Exception ex)
            { }
            return props;
        }
        /// <summary>
        /// 压缩文件成RAR或ZIP文件(需存在Winrar.exe(只要自己电脑上可以解压或压缩文件就存在Winrar.exe))
        /// </summary>
        /// <param name="filesPath">将要压缩的文件夹或文件的绝对路径</param>
        /// <param name="rarPathName">压缩后的压缩文件保存绝对路径（包括文件名称）</param>
        /// <param name="IsCover">所压缩文件是否会覆盖已有的压缩文件(如果不覆盖,所压缩文件和已存在的相同名称的压缩文件不会共同存在,只保留原已存在压缩文件)</param>
        /// <param name="PassWord">压缩密码(如果不需要密码则为空)</param>
        /// <returns>true(压缩成功);false(压缩失败)</returns>
        public static bool CondenseRarOrZip(string filesPath, string rarPathName, bool IsCover, string PassWord)
        {
            string rarPath = Path.GetDirectoryName(rarPathName);
            if (!Directory.Exists(rarPath))
                Directory.CreateDirectory(rarPath);
            Process Process1 = new Process();
            Process1.StartInfo.FileName = "Winrar.exe";
            Process1.StartInfo.CreateNoWindow = true;
            string cmd = "";
            if (!string.IsNullOrEmpty(PassWord) && IsCover)
                //压缩加密文件且覆盖已存在压缩文件( -p密码 -o+覆盖 )
                cmd = string.Format(" a -ep1 -p{0} -o+ {1} {2} -r", PassWord, rarPathName, filesPath);
            else if (!string.IsNullOrEmpty(PassWord) && !IsCover)
                //压缩加密文件且不覆盖已存在压缩文件( -p密码 -o-不覆盖 )
                cmd = string.Format(" a -ep1 -p{0} -o- {1} {2} -r", PassWord, rarPathName, filesPath);
            else if (string.IsNullOrEmpty(PassWord) && IsCover)
                //压缩且覆盖已存在压缩文件( -o+覆盖 )
                cmd = string.Format(" a -ep1 -o+ {0} {1} -r", rarPathName, filesPath);
            else
                //压缩且不覆盖已存在压缩文件( -o-不覆盖 )
                cmd = string.Format(" a -ep1 -o- {0} {1} -r", rarPathName, filesPath);
            //命令
            Process1.StartInfo.Arguments = cmd;
            Process1.Start();
            Process1.WaitForExit();//无限期等待进程 winrar.exe 退出
                                   //Process1.ExitCode==0指正常执行，Process1.ExitCode==1则指不正常执行
            if (Process1.ExitCode == 0)
            {
                Process1.Close();
                return true;
            }
            else
            {
                Process1.Close();
                return false;
            }
        }
        /// 利用 WinRAR 进行压缩  
        /// </summary>  
        /// <param name="path">将要被压缩的文件夹（绝对路径）</param>  
        /// <param name="rarPath">压缩后的 .rar 的存放目录（绝对路径）</param>
        /// <param name="rarName">压缩文件的名称（包括后缀）</param>  
        /// <returns>true 或 false。压缩成功返回 true，反之，false。</returns>
        public static bool RAR(string path, string rarPath, string rarName)
        {
            bool flag = false;
            string rarexe;    //WinRAR.exe 的完整路径  
            RegistryKey regkey; //注册表键  
            Object regvalue;   //键值  
            string cmd;     //WinRAR 命令参数  
            ProcessStartInfo startinfo;
            Process process;
            try
            {
                regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command");
                regvalue = regkey.GetValue(""); // 键值为 "d:\Program Files\WinRAR\WinRAR.exe" "%1"  
                rarexe = regvalue.ToString();
                regkey.Close();
                rarexe = rarexe.Substring(1, rarexe.Length - 7); // d:\Program Files\WinRAR\WinRAR.exe  
                Directory.CreateDirectory(path);
                //压缩命令，相当于在要压缩的文件夹(path)上点右键 ->WinRAR->添加到压缩文件->输入压缩文件名(rarName)  
                cmd = string.Format("a {0} {1} -r", rarName, path);
                startinfo = new ProcessStartInfo();
                startinfo.FileName = rarexe;
                startinfo.Arguments = cmd; //设置命令参数  
                startinfo.WindowStyle = ProcessWindowStyle.Hidden; //隐藏 WinRAR 窗口  
                startinfo.WorkingDirectory = rarPath;
                process = new Process();
                process.StartInfo = startinfo;
                process.Start();
                process.WaitForExit(); //无限期等待进程 winrar.exe 退出  
                if (process.HasExited)
                {
                    flag = true;
                }
                process.Close();
            }
            catch (Exception e)
            {
                throw e;
            }
            return flag;
        }

        /// <summary>
        /// 将目录和文件压缩为rar格式并保存到指定的目录
        /// </summary>
        /// <param name="soruceDir">要压缩的文件夹目录</param>
        /// <param name="rarFileName">压缩后的rar保存路径</param>
        public static void CompressRar(string soruceDir, string rarFileName)
        {
            string regKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe";
            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(regKey);
            string winrarPath = registryKey.GetValue("").ToString();
            registryKey.Close();
            string winrarDir = System.IO.Path.GetDirectoryName(winrarPath);
            String commandOptions = string.Format("a {0} {1} -r", rarFileName, soruceDir);

            ProcessStartInfo processStartInfo = new ProcessStartInfo();
            processStartInfo.FileName = System.IO.Path.Combine(winrarDir, "rar.exe");
            processStartInfo.Arguments = commandOptions;
            processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            Process process = new Process();
            process.StartInfo = processStartInfo;
            process.Start();
            process.WaitForExit();
            process.Close();
        }

        public static void ExcelAddOrderNo(String OrderNo,String SheetName,String FilePath)
        {
            var app = new Application();
            Workbook wbk = app.Workbooks.Open(FilePath);
            Worksheet sheet = wbk.Sheets[SheetName];
            sheet.Cells[7, 5] = "order_no";
            sheet.Cells[8, 5] = OrderNo;
            wbk.Save();
            wbk.Close();

        }

        /// <summary>
        /// 获取文件MD5值
        /// </summary>
        /// <param name="fileName">文件绝对路径</param>
        /// <returns>MD5值</returns>
        public static String GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }
    }
}
